package com.readpost.controller;


import com.readpost.doman.Result;
import com.readpost.doman.Entity.User;
import com.readpost.service.UserService;
import com.readpost.utils.JWTUtil;
import com.readpost.utils.ThreadLocalUtil;
import lombok.extern.log4j.Log4j2;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/user")
@Validated
@Log4j2
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 用户登录
     * 传入用户名和密码信息，返回JWT令牌
     * @param username 用户名
     * @param password 密码
     * @return Result<String> 包含JWT令牌的响应对象
     */
    @PostMapping("/login")
    public Result<String> login(@jakarta.validation.constraints.Pattern(regexp = "^[\\w]{3,10}$") String username,
                              @jakarta.validation.constraints.Pattern(regexp = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{6,16}$") String password){
        User user = userService.userLogin(username,password);
        if(user != null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("userid", user.getUserid());
            claims.put("username", user.getUsername());
            String token = JWTUtil.createJWT(claims);
            return Result.success(token);

        }else{
            return Result.error(400,"用户名或密码错误");
        }
    }


    /**
     * 用户注册
     * @param username 用户名
     * @param password 密码
     * @return Result<String> 返回注册结果信息
     */
    @PostMapping("/register")
    public Result<String> register(String username, String password){
        // 用户名正则：长度 3 到 10 个字符
        Pattern usernamePattern = Pattern.compile("^[\\w]{2,10}$");
        // 密码正则：长度 6 到 16 个字符，至少包含数字、大写字母、小写字母
        Pattern passwordPattern = Pattern.compile("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{6,16}$");
        // 校验用户名
        if (!usernamePattern.matcher(username).matches()) {
            return Result.error(400, "用户名长度需在 3 到 10 个字符之间");
        }
        // 校验密码
        if (!passwordPattern.matcher(password).matches()) {
            return Result.error(400, "密码长度需在 6 到 16 个字符之间，且至少包含数字、大写字母和小写字母");
        }
        User name = userService.getUserByUsername(username);
        if (name!=null){
            return Result.error(400,"用户名已存在");
        }else {
            userService.userRegister(username,password);
            return Result.success();
        }
    }


    /**
     * 获取用户信息
     */
    @GetMapping("/userInfo")
    public Result<User> getUserInfo( /* @RequestHeader("Authorization") String token**/){
        Map<String,Object> map =ThreadLocalUtil.get();
        Integer userid = (Integer) map.get("userid");
//        Map<String, Object> claims = JWTUtil.verifyJWT(token);
//        Integer userid = (Integer) claims.get("userid");
        User user = userService.getUserById(userid);
        return Result.success(user);
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/upUserInfo")
    public Result<String> updateUserInfo(@RequestBody @Validated User user){
        Map<String,Object> map =ThreadLocalUtil.get();
        Integer userid = (Integer) map.get("userid");
        userService.updateUser(user,userid);
        return Result.success();
    }


    /**
     * 更新用户头像
     */
    @PatchMapping("/updateAvatar")
    public Result<String> updatePicture(@RequestParam @URL String avatarUrl){
        Map<String,Object> map =ThreadLocalUtil.get();
        Integer userid = (Integer) map.get("userid");
        userService.updatePicture(avatarUrl,userid);
        return Result.success(avatarUrl);
    }


    /**
     * 更新用户密码
     * Validated 用于验证请求参数是否符合指定的约束条件
     * RequestBody 用于将请求体中的 JSON 数据绑定到方法参数上
     */
    @PostMapping("/upPwd")
    public Result<String> updatePwd(@RequestBody @Validated Map<String,Object> pwdParams){
        userService.updatePwd(pwdParams);
        return Result.success();
    }

    /**
     * 发送邮箱验证码
     */
    @PostMapping("/sendEmailCode")
    public Result<String> sendEmailCode(@RequestBody @Validated Map<String,Object> emailParams){
        Map<String,Object> map =ThreadLocalUtil.get();
        Integer userid = (Integer) map.get("userid");
        userService.sendEmailCode(emailParams,userid);
        return Result.success();
    }


    /**
      绑定邮箱
     */
    public Result<String> bindEmail(@RequestBody @Validated Map<String,Object> emailParams){
        userService.bindEmail(emailParams);
        return Result.success();
    }

}
